//$URL: https://dasding.googlecode.com/svn/trunk/data/dao/mongoDB/src/main/java/de/piratech/dasding/data/database/mongo/UserDataImpl.java $
//$Id: UserDataImpl.java 116 2013-03-30 14:21:01Z krieg.maria@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.data.database.mongo;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.DB;

import de.piratech.dasding.data.Action;
import de.piratech.dasding.data.Event;
import de.piratech.dasding.data.Location;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.data.database.LocationData;
import de.piratech.dasding.data.database.UserData;
import de.piratech.dasding.data.database.mongo.data.MongoLocation;

/**
 */
public class LocationDataImpl extends AbstractMongoDB<MongoLocation, Location>
    implements LocationData {

  private static final Logger LOG = LoggerFactory.getLogger(UserData.class);

  public LocationDataImpl(DB pDB) {
    super(pDB, MongoLocation.class, COLLECTIONS.LOCATION_COLLECTION);
  }

  @Override
  public Location createLocation(Location pUser) throws DatabaseException {
    LOG.debug("createUser({})", pUser);
    return getDBCollection().insert(new MongoLocation(pUser)).getSavedObject()
        .getDataObject();
  }

  @Override
  public void deleteLocation(Location pUser) throws DatabaseException {
    List<Event> events = new EventDataImpl(db).findByLocation(pUser);
    List<Action> actions = new ActionDataImpl(db).findByLocation(pUser);

    if (events != null && events.size() > 0) {
      throw new DatabaseException("has related events");
    }
    if (actions != null && actions.size() > 0) {
      throw new DatabaseException("has related actions");
    }

    getDBCollection().removeById(pUser.getId());
  }

  @Override
  public void updateLocation(Location pUser) {
    LOG.debug("updateUser({})", pUser);
    getDBCollection().updateById(pUser.getId(), new MongoLocation(pUser));
  }

  @Override
  public Location getLocation(String pName) {
    LOG.debug("getUser({})", pName);
    return getDBCollection().findOneById(pName).getDataObject();
  }

  @Override
  public List<Location> getLocations() throws DatabaseException {
    List<MongoLocation> array = getDBCollection().find().toArray();
    List<Location> list = getDataObjectList(array);
    return list;
  }
}
